package com.yuandengta.yomall.auth.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.constant.AuthConstant;
import com.yuandengta.common.utils.HttpUtils;
import com.yuandengta.common.utils.JsonUtils;
import com.yuandengta.common.utils.R;
import com.yuandengta.common.vo.MemberVO;
import com.yuandengta.yomall.auth.feign.MemberFeignService;
import com.yuandengta.yomall.auth.vo.WeiboUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录 {@link OAuth2Controller}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 微博登录
     * @param code
     * @param session
     * @return
     */
    @GetMapping("/oauth/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) {
        Map<String, String> body = new HashMap<>();
        body.put("client_id", "767355573");
        body.put("client_secret", "bb09f12990562e380984ed17844595a1");
        body.put("grant_type", "authorization_code");
        body.put("redirect_uri", "http://auth.yomall.com/oauth/weibo/success");
        body.put("code", code);
        try {
            // 根据code换取access_token
            HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post",
                    new HashMap<String, String>(), null, body);
            // 处理响应
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取到access_token
                String json = EntityUtils.toString(response.getEntity());
                WeiboUser weiboUser = JsonUtils.jsonToPojo(json, WeiboUser.class);

                // 登录或者注册
                // 当前用户第一次登录网站，自动注册，为当前用户生成一个会员信息账号
                R r = memberFeignService.weiboLogin(weiboUser);
                MemberVO memberVO = r.getData("data", new TypeReference<MemberVO>() {});
                session.setAttribute(AuthConstant.SESSION_LOGIN_USER, memberVO);
                // 登录成功重定向到首页
                return "redirect:http://yomall.com";
            } else {
                return "redirect:http://auth.yomall.com/login.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
